<!-- 云模型创建类型 -->
<template>
  <el-dialog
    class="dialogAdapter"
    destroy-on-close
    @close="handleCancel"
    style="border-radius: 10px"
    v-model="props.visible"
    :title="`${type === 'add' ? '创建' : '编辑'}`"
  >
    <!--云模型from -->
    <el-form ref="ruleFormRef" :model="modelForm" :rules="rules" label-position="top">
      <!-- @vue-ignore -->
      <el-upload
        class="avatar-uploader"
        action="#"
        :before-upload="beforeAvatarUpload"
        :http-request="handleRequestUpload"
        accept="image/jpg, image/jpeg, image/png"
        :show-file-list="false"
      >
        <img v-if="modelForm.avatar && isShowAvatar" :src="modelForm?.avatar" class="cover-img" />
        <img v-if="modelForm.avatar && isShowAvatar" :src="EditAvatarSvg" alt="" class="edit-svg" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>

      <el-form-item prop="nickname" label="姓名">
        <el-input v-model="modelForm.nickname" autocomplete="off" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item style="margin-top: 20px" label="语音模型" prop="robot_id">
        <el-select style="width: 100%; border-radius: 6px" v-model="modelForm.robot_id" placeholder="请选择语音模型">
          <el-option v-for="item in voiceModel" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="模型列表" prop="model_id">
        <el-select style="width: 100%; border-radius: 6px" v-model="modelForm.model_id" placeholder="请选择模型">
          <el-option v-for="item in vHumanModel" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="info" label="备注">
        <el-input v-model="modelForm.info" type="textarea" placeholder="请填写智能体备注" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="danger"
          :loading="btnLoading"
          :disabled="shouldDisableButton"
          @click="handleSubmitForm(ruleFormRef)"
        >
          {{ type === "add" ? "创建" : "编辑" }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { VHuManAddAndUpdateApi } from "@/api/vhuman"
import EditAvatarSvg from "@/assets/drawing/edit.svg"
import { useDigitalStore } from "@/store/modules/digital"
import { generateRule } from "@/utils"
import debounce from "@/utils/debounce"
import { ElMessage, FormRules, UploadProps, type FormInstance } from "element-plus"
import { computed, reactive, ref } from "vue"

export interface ModelFormProps {
  avatar: any
  nickname: string
  info?: string
  model_id: number
  robot_id?: number
  id?: number
  isShowAvatar?: boolean
}

interface Props {
  editData?: ModelFormProps
  type?: "add" | "edit"
  visible: boolean
}

const { voiceModel, vHumanModel } = useDigitalStore()

const props = defineProps<Props>()
const emits = defineEmits(["editDpData", "close", "update-init"])
const ruleFormRef = ref<any>(null)
const btnLoading = ref<boolean>(false)
const isShowAvatar = ref<boolean>(Boolean(props.editData && props.editData.isShowAvatar) as any)
const modelForm = ref<ModelFormProps>(props.editData as ModelFormProps)
const avatarImgFile = ref<any>(null)

const rules = reactive<FormRules<ModelFormProps>>({
  nickname: generateRule("姓名"),
  robot_id: generateRule("语音模型"),
  info: generateRule("备注"),
  model_id: generateRule("模型列表")
})

const shouldDisableButton = computed(() => {
  const { avatar, nickname, info, model_id, robot_id } = modelForm.value

  const isNonEmptyString = (value: any) => {
    return typeof value === "string" && value.trim() !== ""
  }

  const isNonEmptyArray = (value: any) => {
    return Array.isArray(value) && value.length > 0
  }

  return (
    ![avatar, nickname, info, model_id, robot_id].every((value) => {
      return isNonEmptyString(value) || isNonEmptyArray(value) || typeof value === "number"
    }) || !isShowAvatar.value
  )
})

// 上传头像之前
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const image = new Image()
  const reader = new FileReader()

  return new Promise((resolve, reject) => {
    reader.onload = (e) => {
      if (typeof reader.result === "string") {
        image.src = reader.result
        image.onload = () => {
          const width = image.width
          const height = image.height
          if (width !== height) {
            ElMessage.error("头像图片必须为(1:1比例)")
            reject()
          } else {
            resolve()
          }
        }
      } else {
        reject()
      }
    }

    reader.readAsDataURL(rawFile)
  })
}

// 上传头像
const handleRequestUpload = debounce((file: any) => {
  if (file) {
    const allowedFormats = ["image/jpeg", "image/jpg", "image/png"]
    if (!allowedFormats.includes(file.file?.type)) {
      ElMessage({
        type: "error",
        message: "格式错误，只能上传 jpeg / jpg / png 图片格式"
      })
      return
    }

    const URL = window.URL || window.webkitURL
    avatarImgFile.value = file.file
    const imgSrc = URL.createObjectURL(file.file)
    isShowAvatar.value = true
    modelForm.value.avatar = imgSrc
  }
}, 300)

// 提交表单按钮
const handleSubmitForm = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        btnLoading.value = true
        // if (avatarImgFile.value instanceof File) {
        //   modelForm.value.avatar = avatarImgFile.value
        // } else {
        //   modelForm.value.avatar = JSON.stringify({})
        // }

        // 提交表单数据时，移除自定义参数
        delete modelForm.value.isShowAvatar

        if (props.type === "add") {
          await VHuManAddAndUpdateApi({ ...modelForm.value, avatar: avatarImgFile.value }, "add")
        } else {
          let avatar: any = null
          if (avatarImgFile.value instanceof File) {
            avatar = avatarImgFile.value
          } else {
            avatar = JSON.stringify({})
          }
          await VHuManAddAndUpdateApi({ ...modelForm.value, avatar, id: modelForm.value.id }, "update")
        }
        ElMessage({
          type: "success",
          message: `${props.type === "add" ? "新增" : "编辑"}成功`
        })
        handleClose("digital_update_init")
      } catch (error: any) {
        ElMessage({
          type: "error",
          message: error.message || "异常错误"
        })
      } finally {
        btnLoading.value = false
      }
    } else {
      console.log("error submit!")
      return false
    }
  })
}, 300)

const handleClose = (type: string) => {
  emits("close", type)
  if (type) {
    handleCancel()
  }
}

const handleCancel = () => {
  if (ruleFormRef.value) {
    modelForm.value = {
      avatar: "",
      nickname: "",
      model_id: -1,
      robot_id: undefined,
      info: "",
      id: undefined
    }
    avatarImgFile.value = null
    isShowAvatar.value = false
    ruleFormRef.value.resetFields() // 重置表单
  }
  handleClose("")
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  position: relative;
  text-align: center;
  margin-bottom: 20px;

  .cover-img {
    width: 80px;
    height: 80px;
    border-radius: 20px;
  }

  .edit-svg {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 32px;
    height: 32px;
    border-radius: 20px 0px;
    opacity: 0.8;
  }
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 20px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>
